import React from 'react';
import { toJS } from 'mobx'
import { inject, observer } from 'mobx-react';
import { withRouter } from 'react-router-dom';
import { Icon, Tools, SearchBar, List, Picker, Popover, Avatar, NoticeBar, Modal } from 'weaver-mobile';
import { SearchAdvanced, ListViewPage } from 'weaver-mobile-page';
import { renderLoadingDef, renderNoDataDef } from '../../public/BlogUtils';
import WeaUtils from '../../public/BlogUtils';
import AttentionTool from '../../public/ShareToMeTool';
import HisBlogRoute from '../../hisBlog/HisBlogRoute';
import OverView from '../blogAttention/OverView';
import NewAttentionTool from '../../public/NewAttentionTool'
const getLabel = Tools.getLabel;
window.WeaUtils = WeaUtils;

const store = [
  'blogHomeStore',
  'blogShareToMeStore',
   'blogAttentionStore'
]

@withRouter
@inject(...store)
@observer
export default class ShareToMe extends React.Component {
  static defaultProps = {
    prefixCls: 'blog-center-attention-myAttention'
  }

  constructor(props) {
    super(props);
    this.state = {
      groupId: 'all',
      groupName: getLabel(384389, '全部关注'),
      filterVisible: 0, // 是否展示高级搜索
      visible: false,
      popover: 0, //1:查看微博总览 2：批量 0：我的关注
      path: props.parentPath + "/hisBlog/",
      userId: '',
    }
    this.updateUserAttentionStatus = this.updateUserAttentionStatus.bind(this);
  }

  componentDidMount() {
    const { blogShareToMeStore: { initalMyAttention } } = this.props;
    initalMyAttention();
  }

  componentWillUnmount() {
    const { blogShareToMeStore: { clearMyAttention } } = this.props;
    clearMyAttention();
  }

  onSelect=(opt,index)=>{
    let {  blogShareToMeStore: { getAttentionCountInfos, setStoreState, MyAttentionIsSearch, initalMyAttentionList, myAttentionSelectNone } } = this.props;
    const { filterVisible } = this.state;
    if (index === 0 && filterVisible === 0) { // 查看微博总览
      setStoreState({ overviewAdValue: '', isSearch: false, overviewFlag: 0 });
      //this.setState({ filterVisible: 1, visible:false, popover: 1 })
      //getAttentionCountInfos();
      this.props.history.push({pathname:'/userCenter/shareToMe/shareToMeWeibo'});
    }else if (index === 1) {
        this.props.history.push({pathname:'/userCenter/shareToMe/batchAttention'});
    }
  }

  // 我的关注--更改关注状态
  updateUserAttentionStatus(attnInfo) {
    const { blogShareToMeStore: { updateUserAttentionStatus } } = this.props;
    updateUserAttentionStatus(attnInfo);
  }

  // 我的关注--分组搜索
  onPickerChange = (val,group) => {
    const { blogShareToMeStore: { initalMyAttentionList, setStoreState,changeMyGroup } } = this.props;
    let groupName = val[0].split('(')[0];
    toJS(group).forEach(item=>{
      if(groupName===item.groupName) {
        changeMyGroup({groupId: item.groupId,groupName: item.groupName})
        this.setState({groupId: item.groupId,groupName: item.groupName})
        initalMyAttentionList({groupId: item.groupId})
        setStoreState({groupSearch: true})
      }
    })
  }

  // 我的关注--批量取消关注
  cancelAttention = (idSet) => {
    const { blogShareToMeStore: { batchCancelAttn, initalMyAttentionList } } = this.props;
    Modal.alert(getLabel(390696, '取消关注后需要重新申请才能再次关注'),getLabel(129256, '确定要取消吗？'),
      [
        {text: getLabel(31129, '取消')},
        {text: getLabel(33703, '确认'), onPress: () => batchCancelAttn({ idSet }, () => initalMyAttentionList({ groupId: 'all' }))}
      ]
    );
  }

  // 我的关注--移动 / 复制到组 key: 1 移动 2 复制 
  onOk = (val, key, idSet) => {
    let { blogShareToMeStore: { moveContactToBlogGroup, copyContactToBlogGroup, groupData, initalMyAttentionList }} = this.props;
    let groupName = val[0].split('(')[0];
    groupData.map(item => {
      if (groupName === item.groupName) {
        key === 1 ? 
        moveContactToBlogGroup({idSet, sourceGroup: 'all', destGroup: item.groupId},() => {initalMyAttentionList({ groupId: item.groupId });this.setState({groupName:item.groupName,groupId: item.groupId})}) :
        copyContactToBlogGroup({idSet, destGroup: item.groupId}, () => {initalMyAttentionList({ groupId: item.groupId });this.setState({groupName:item.groupName,groupId: item.groupId})});
      }
    });
  }

    goToUser = (userid) => {
        this.setState({ userId: userid }, () => {
            this.props.history.push(this.state.path + userid);
        });
    }

  choseTab = () => {
    this.props.history.push({pathname:"/userCenter/blogAttention/attention",query: { name : 'special' }});
  }
    // 我的关注--列表模板
  getTemplate = () => {
    const listStyle = 'blog-list-line';
    const ddd=this.goToUser;
    const newTemp = {
      default: [{
        key: 'col_1',
        render: (data) => {
          const { imageUrl, lastname, deptName, jobtitle, islower, userId, attentionStatus, isreceive,username,specialStatus} = data;
          return (
            <div className={listStyle}>
              <div className={`${listStyle}-userInfo`} onClick={() => {
                  ddd(userId);
              }}>
                <Avatar userId={userId} />
                <div className={`${listStyle}-userInfo-content`}>
                  <span className='lastName text-wrap'>{username}</span>
                  <span className='departmentName text-wrap'>{deptName}&nbsp;{jobtitle}</span>
                </div>
              </div>
              <div className={`${listStyle}-ops`}>
                <AttentionTool 
                  isreceive={isreceive} 
                  attentionStatus={attentionStatus} 
                  userId={userId}
                  islower={islower}
                  type={"share"}
                  callback={this.updateUserAttentionStatus}
                />
              </div>
                <NewAttentionTool
                    specialStatus={specialStatus}
                    choseTab={this.choseTab}
                    isreceive={isreceive}
                    attentionStatus={attentionStatus}
                    userId={userId}
                    islower={islower}
                    type={"share"}
                    callback={this.updateUserAttentionStatus}
                />
            </div>
          )
        }
      }]
    }
    return newTemp;
  }

  /* 我的关注页面 */
  pickerContent = () => {
    const { prefixCls, blogShareToMeStore: { groupData, MyAttentionIsSearch, shareToMeList, showChecked, myAttentionSelectAll, myAttentionSelectNone, myAttentionCancel, myAttentionLoading, groupSearch, myAttentionSearchNextPage, myAttentionSearch } } = this.props;
    let group = groupData || '', AttentionGroup = [];
    const datas = toJS(shareToMeList.data);
    const myAttentionSelectedKeys = toJS(shareToMeList.selectedRowKeys);
    const idSet = myAttentionSelectedKeys.join(',');
    const myAttentionClass = `${prefixCls}-user-list ${!MyAttentionIsSearch && showChecked && 'blog-list-checked'} ${MyAttentionIsSearch && 'blog-center-attention-myAttention-search-list'} ${MyAttentionIsSearch && showChecked && 'blog-list-checked-search'}`;
    group.forEach(item => {
      let { groupCount, groupName } = item;
      groupName = groupName + '(' + groupCount + ')';
      AttentionGroup.push({value:groupName, label:groupName});
    });
    const getBtn = (type, text) => (
      <div className={`${prefixCls}-user-btns-item`}>
        <Icon type={type} size='xs'/>
        <div>{text}</div>
      </div>
    )
    const getMoveCopy = (key, idSet) => {
      return (
        <Picker
          data={AttentionGroup}
          cols={1}
          disabled={!idSet || idSet === ''}
          onOk={val => this.onOk(val, key, idSet)}
        >
         {key === 1 ? getBtn('blog-yidong', getLabel(-81296,'移动到组')) : getBtn('blog-fuzhi', getLabel(31267,'复制到组'))} 
        </Picker>
      );
    }
    return (!myAttentionLoading && datas.length === 0 && !groupSearch) ? renderNoDataDef : (
      <div ref='myAttention' style={{top:'69.5px'}} className={`${prefixCls}-user`}>
       
        <div className={myAttentionClass}  style={{top:'0px'}}>
          {
            myAttentionLoading ? renderLoadingDef : (
              <ListViewPage.Normal
                store={shareToMeList}
                getDataCustom={true}
                getTemplate={this.getTemplate}
                customHeight='100%'
                rowKey='userId'
                showCheck={showChecked}
                onEndReached={MyAttentionIsSearch ? myAttentionSearchNextPage : null}
                onRefresh={myAttentionSearch}
              />
            )
          }
        
        </div>
      </div>
    )
  }
 
  render() {
    let { prefixCls, blogShareToMeStore: { loading, groupData, search, updateAdSearchSubject, isSearch, setStoreState, overviewAdValue, overViewSearch, overviewFlag, myAttentionSearch } } = this.props;
    let { filterVisible, visible, popover } = this.state;
    let group = groupData || '', AttentionGroup = [];
    group.forEach(item => {
      let { groupCount, groupName } = item;
      groupName = groupName + '(' + groupCount + ')';
      AttentionGroup.push({value:groupName, label:groupName});
    });
    const extraBtn = [
      { 
        key: 'advanced', 
        show: filterVisible === 1 ? <Icon key='filter-o' type='filter-o' onClick={()=>this.props.history.push(search.path)} /> : '' 
      },
      { 
        key: 'drop',
        show: (
          <Popover 
            mask
            visible={visible}
            overlay={ [
              <Popover.Item>{getLabel(390697,'查看微博总览')}</Popover.Item>,
              <Popover.Item>{getLabel(31914,'批量操作')}</Popover.Item>
            ] 
            }
            onSelect={(v,index) => this.onSelect(v,index)}
          >
            <Icon key='ellipsis' type='ellipsis' />
          </Popover>
        ),
      },
    ];
    const btnGroup = [
      { key: 'reset',
        text: getLabel(2022,"重置"),
        onClick: () => {
          search.form.resetFields();
          setStoreState({overviewAdValue: ''})
        }
      },
      { key: 'submit',
        type: 'primary',
        text: getLabel(826,"确定"),
        onClick: () => {
          setStoreState({overviewFlag: ++overviewFlag});
          overViewSearch(() => this.props.history.go(-1));
        },
      }
    ];
    return loading ? renderLoadingDef : (
    
      <div className='blog-center-myFans'>
       <div>
         <div style={{backgroundColor:'#717171',color:'#FFFFFF',height:'25px',display: 'flex',justifyContent: 'center',alignItems: 'center'}}>{getLabel(513653, '分享给我')}</div>
        <SearchBar
          value={overviewAdValue}
          placeholder = {getLabel(500351,'请输入关键字')} 
          onChange={val => updateAdSearchSubject(val)}
          onSubmit={value => {
              setStoreState({myAttentionLoading: true})
              myAttentionSearch(value);
              this.setState({groupId: 'all',groupName: getLabel(384389, '全部关注'),})
          }}
          showExtraButton
          extraButton={extraBtn}
        />
        <SearchAdvanced
          store={search}
          buttonGroupData={btnGroup} 
          onChange={(condition, value) => {
            if(condition.domkey[0] === 'content') { 
              setStoreState({ overviewAdValue: value }); 
            }
          }}
        />
        { popover === 0 && this.pickerContent()}
        { popover === 1 && <OverView isSearch={isSearch}/>}
        <HisBlogRoute path={this.state.path} userId={this.state.userId}/>
      </div>
      </div>
    )
  }
}